<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="盐度" prop="salinity">
        <el-input
          v-model="queryParams.salinity"
          placeholder="请输入盐度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="PH值" prop="ph">
        <el-input
          v-model="queryParams.ph"
          placeholder="请输入PH值"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="溶氧" prop="dissolvedOxygen">
        <el-input
          v-model="queryParams.dissolvedOxygen"
          placeholder="请输入溶氧"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="氨氮" prop="ammonia">
        <el-input
          v-model="queryParams.ammonia"
          placeholder="请输入氨氮"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="亚硝酸盐" prop="nitrite">
        <el-input
          v-model="queryParams.nitrite"
          placeholder="请输入亚硝酸盐"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->

      <el-form-item>
        <!-- <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button> -->
        <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
        <el-button type="success" plain @click="startAutoRefresh">开启自动刷新</el-button>
        <el-button type="danger" plain @click="stopAutoRefresh">停止自动刷新</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="SysWaterQualityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="记录ID" align="center" prop="id" /> -->
      <el-table-column label="桶编号" align="center" prop="tankCode" />
      <el-table-column label="水温" align="center" prop="temperature" />
      <el-table-column label="盐度" align="center" prop="salinity" />
      <el-table-column label="PH值" align="center" prop="ph" />
      <el-table-column label="溶氧" align="center" prop="dissolvedOxygen" />
      <el-table-column label="氨氮" align="center" prop="ammonia" />
      <el-table-column label="亚硝酸盐" align="center" prop="nitrite" />
      <el-table-column label="记录时间" align="center" prop="recordTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['SysWaterQuality:SysWaterQuality:edit']">修改</el-button> -->
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['SysWaterQuality:SysWaterQuality:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改水质实时数据对话框 -->
      <!-- <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="SysWaterQualityRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="桶ID" prop="tankId">
          <el-select
            v-model="form.tankId"
            placeholder="请选择桶ID"
            @change="handleTankIdChange"
          >
            <el-option
              v-for="tank in tankOptions"
              :key="tank.tankId"
              :label="tank.tankId"
              :value="tank.tankId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="桶编号" prop="tankCode">
          <el-select
            v-model="form.tankCode"
            placeholder="请选择桶编号"
            disabled
          >
            <el-option
              v-for="tank in tankOptions"
              :key="tank.tankCode"
              :label="tank.tankCode"
              :value="tank.tankCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="水温" prop="temperature">
          <el-input v-model="form.temperature" placeholder="请输入水温" />
        </el-form-item>
        <el-form-item label="盐度" prop="salinity">
          <el-input v-model="form.salinity" placeholder="请输入盐度" />
        </el-form-item>
        <el-form-item label="PH值" prop="ph">
          <el-input v-model="form.ph" placeholder="请输入PH值" />
        </el-form-item>
        <el-form-item label="溶氧" prop="dissolvedOxygen">
          <el-input v-model="form.dissolvedOxygen" placeholder="请输入溶氧" />
        </el-form-item>
        <el-form-item label="氨氮" prop="ammonia">
          <el-input v-model="form.ammonia" placeholder="请输入氨氮" />
        </el-form-item>
        <el-form-item label="亚硝酸盐" prop="nitrite">
          <el-input v-model="form.nitrite" placeholder="请输入亚硝酸盐" />
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker clearable
            v-model="form.recordTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择记录时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog> -->
  </div>
</template>

<script setup name="SysWaterQuality">
import { listSysWaterQuality, getSysWaterQuality, delSysWaterQuality, addSysWaterQuality, updateSysWaterQuality } from "@/api/SysWaterQuality/SysWaterQuality"
import { listSysTanks } from "@/api/SysTanks/SysTanks"

const { proxy } = getCurrentInstance()

const SysWaterQualityList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const tankOptions = ref([])

// 控制自动刷新
const autoRefresh = ref(true)
const timer = ref(null)

// 查询参数和表单数据
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    tankId: null,
    temperature: null,
    salinity: null,
    ph: null,
    dissolvedOxygen: null,
    ammonia: null,
    nitrite: null,
    recordTime: null,
    tankCode: null,
  },
  rules: {}
})

const { queryParams, form, rules } = toRefs(data)

/** 查询水质实时数据列表 */
function getList() {
  loading.value = true
  listSysWaterQuality(queryParams.value).then(response => {
    SysWaterQualityList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    tankId: null,
    tankCode: null,
    temperature: null,
    salinity: null,
    ph: null,
    dissolvedOxygen: null,
    ammonia: null,
    nitrite: null,
    recordTime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  }
  proxy.resetForm("SysWaterQualityRef")
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  loadTankOptions().then(() => {
    open.value = true
    title.value = "添加水质实时数据"
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  Promise.all([
    getSysWaterQuality(_id),
    loadTankOptions()
  ]).then(([response]) => {
    // 确保返回的数据是对象
    if (response.data && typeof response.data === 'object') {
      form.value = response.data
    }

    // 设置当前选择的tankId对应的tankCode
    const selectedTank = tankOptions.value.find(tank => tank.tankId === form.value.tankId)
    if (selectedTank) {
      form.value.tankCode = selectedTank.tankCode
    }

    open.value = true
    title.value = "修改水质实时数据"
  }).catch(err => {
    console.error('修改数据失败:', err)
    proxy.$modal.msgError('获取数据失败')
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SysWaterQualityRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateSysWaterQuality(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSysWaterQuality(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除水质实时数据编号为"' + _ids + '"的数据项？').then(function() {
    return delSysWaterQuality(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('SysWaterQuality/SysWaterQuality/export', {
    ...queryParams.value
  }, `SysWaterQuality_${new Date().getTime()}.xlsx`)
}

/** 开启自动刷新 */
function startAutoRefresh() {
  clearInterval(timer.value)
  timer.value = setInterval(() => {
    getList()
  }, 5000)
  autoRefresh.value = true
}

/** 停止自动刷新 */
function stopAutoRefresh() {
  clearInterval(timer.value)
  timer.value = null
  autoRefresh.value = false
}

// 页面挂载时启动自动刷新
onMounted(() => {
  if (autoRefresh.value) {
    startAutoRefresh()
  }
})

// 页面卸载时清理定时器
onUnmounted(() => {
  stopAutoRefresh()
})

// 获取养殖桶列表
function loadTankOptions() {
  return listSysTanks({
    pageSize: 10000 // 获取所有养殖桶数据
  }).then(response => {
    console.log('养殖桶列表数据:', response)
    // 确保返回的数据是数组
    if (Array.isArray(response.rows)) {
      tankOptions.value = response.rows.map(tank => ({
        tankId: tank.tankId,
        tankCode: tank.tankCode
      }))
    } else {
      tankOptions.value = []
    }
  }).catch(err => {
    console.error('获取养殖桶列表失败:', err)
    proxy.$modal.msgError('获取养殖桶列表失败')
    tankOptions.value = []
  })
}

// 桶ID变化时更新桶编号
function handleTankIdChange(value) {
  const selectedTank = tankOptions.value.find(tank => tank.tankId === value)
  if (selectedTank) {
    form.value.tankCode = selectedTank.tankCode
  } else {
    form.value.tankCode = null
  }
}

// 初始化数据
getList()
</script>
